package com.hjq.demo.ui.activity

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.speech.tts.UtteranceProgressListener
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import androidx.appcompat.widget.AppCompatSeekBar
import androidx.appcompat.widget.AppCompatSpinner
import com.blankj.utilcode.util.AppUtils
import com.google.android.material.button.MaterialButton
import com.google.android.material.textview.MaterialTextView
import com.hjq.base.BaseDialog
import com.hjq.demo.BuildConfig
import com.hjq.demo.R
import com.hjq.demo.app.AppActivity
import com.hjq.demo.http.WebSocketManager
import com.hjq.demo.manager.ActivityManager
import com.hjq.demo.manager.MmkvUtil
import com.hjq.demo.ui.act.AppListAct
import com.hjq.demo.ui.act.MainAct
import com.hjq.demo.ui.dialog.InputDialog
import com.hjq.demo.worktask.TaskGoHome
import com.hjq.http.EasyConfig
import com.hjq.language.LocaleContract
import com.hjq.language.MultiLanguages
import com.hjq.toast.ToastUtils
import com.hjq.widget.view.SwitchButton
import timber.log.Timber
import java.io.DataOutputStream
import java.io.File
import java.io.IOException
import java.util.Locale


/**
 *  管理员界面
 */
class AdminActivity : AppActivity() {
    private val btn_back: MaterialButton? by lazy { findViewById(R.id.btn_back) }
    private val btn_rom: MaterialButton? by lazy { findViewById(R.id.btn_rom) }
    private val btn_launcher: MaterialButton? by lazy { findViewById(R.id.btn_launcher) }
    private val btn_order: MaterialButton? by lazy { findViewById(R.id.btn_order) }
    private val btn_sys_setting: MaterialButton? by lazy { findViewById(R.id.btn_sys_setting) }
    private val btn_sn: MaterialButton? by lazy { findViewById(R.id.btn_sn) }
    private val bt_zh: MaterialButton? by lazy { findViewById(R.id.bt_zh) }
    private val bt_laji: MaterialButton? by lazy { findViewById(R.id.bt_laji) }
    private val bt_en: MaterialButton? by lazy { findViewById(R.id.bt_en) }
    private val bt_ko: MaterialButton? by lazy { findViewById(R.id.bt_ko) }
    private val btn_apps: MaterialButton? by lazy { findViewById(R.id.btn_apps) }
    private val bt_simple: MaterialButton? by lazy { findViewById(R.id.bt_simple) }
    private val btn_speed: MaterialButton? by lazy { findViewById(R.id.btn_speed) }
    private val btn_restart: MaterialButton? by lazy { findViewById(R.id.btn_restart) }
    private val btn_applist: MaterialButton? by lazy { findViewById(R.id.btn_applist) }

    private val tv_root: MaterialTextView? by lazy { findViewById(R.id.tv_root) }
    private val seek: AppCompatSeekBar? by lazy { findViewById(R.id.seek) }
    private val switch_auto: SwitchButton? by lazy { findViewById(R.id.switch_auto) }
    private val switch_log: SwitchButton? by lazy { findViewById(R.id.switch_log) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_admin
    }

    private var speedPicth = 0f;
    override fun initView() {
        switch_auto?.setChecked(MmkvUtil.getBool(MmkvUtil.IsBackCheck))
        btn_applist?.setOnClickListener {
            startActivity(AppListAct::class.java)
        }
        switch_auto?.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener {
            override fun onCheckedChanged(button: SwitchButton, checked: Boolean) {
                MmkvUtil.save(MmkvUtil.IsBackCheck, checked)
            }

        })
        switch_log?.setChecked(MmkvUtil.getBool(MmkvUtil.DeveloperOpenDebug))

        switch_log?.setOnCheckedChangeListener(object : SwitchButton.OnCheckedChangeListener {
            override fun onCheckedChanged(button: SwitchButton, checked: Boolean) {
                MmkvUtil.save(MmkvUtil.DeveloperOpenDebug, checked)
                restartApp()
            }

        })
        tv_root?.text =
            "Superuser:${checkRootPermission()} 是否root:  ${AppUtils.isAppRoot()},SU:${isSuEnable()}"
        btn_speed?.setOnClickListener {
            play("我于杀戮之中盛放，亦如黎明中的花朵!")
        }
        btn_rom?.setOnClickListener {
//            startActivity(com.softwinner.timerswitch.ui.TimerSwitchActivity::class.java)
        }
        btn_restart?.setOnClickListener {
//            restart() https://blog.csdn.net/guang09080908/article/details/41413025
            setTimeWake();
            shutdown();
        }
        seek?.setOnSeekBarChangeListener(object : OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                Timber.d("onProgressChanged " + progress)
                speedPicth = progress.toFloat()
                btn_speed?.text = "测试音调 ：$speedPicth ";
                toSpeech = null;
                initTextToSpeech()
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {
                Timber.d("onStartTrackingTouch ")
            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                Timber.d("onStopTrackingTouch ")
            }

        })
        btn_apps?.setOnClickListener {
//            startActivity(MainHideActivity::class.java)
        }
        btn_order?.setOnClickListener {

            val seconds = System.currentTimeMillis() / 1000 //实时时间戳
//        val orderSeconds = miniutesLong.toLong() * 60;// 订单时长：秒
            val endTimestamp = seconds + 60 * 1
            MmkvUtil.saveLong(MmkvUtil.EndTime, endTimestamp);
            TaskGoHome.goMain(66)

            ActivityManager.getInstance().finishAllActivities()
            startActivity(MainAct::class.java)


        }
        btn_back?.setOnClickListener {
            onBackPressedDispatcher.onBackPressed()
        }
        bt_simple?.setOnClickListener {
//             切换中文 繁體
            val restart = MultiLanguages.setAppLanguage(
                this, LocaleContract.getSimplifiedChineseLocale()
            )
            if (restart) {
                EasyConfig.getInstance().addHeader("language", "zh")
                ActivityManager.getInstance().finishAllActivities()
//                startActivity(SplashActivity::class.java)
                startActivity(AdminActivity::class.java)
            }
        }
        bt_zh?.setOnClickListener {
//             切换中文 繁體
            val restart = MultiLanguages.setAppLanguage(
                this, LocaleContract.getTraditionalChineseLocale()
            )
            if (restart) {
                EasyConfig.getInstance().addHeader("language", "tw")
                ActivityManager.getInstance().finishAllActivities()
//                startActivity(SplashActivity::class.java)
                startActivity(AdminActivity::class.java)
            }
        }
        bt_ko?.setOnClickListener {
//             切换
            val restart = MultiLanguages.setAppLanguage(
                this, LocaleContract.getKoreanLocale()
            )
            if (restart) {
                EasyConfig.getInstance().addHeader("language", "ko")
                ActivityManager.getInstance().finishAllActivities()
//                startActivity(SplashActivity::class.java)
                startActivity(AdminActivity::class.java)
            }
        }
        bt_laji?.setOnClickListener {
//             切换 廁所語言
            val restart = MultiLanguages.setAppLanguage(
                this, LocaleContract.getJapaneseLocale()
            )
            if (restart) {
                EasyConfig.getInstance().addHeader("language", "wc")
                ActivityManager.getInstance().finishAllActivities()
//                startActivity(SplashActivity::class.java)
                startActivity(AdminActivity::class.java)
            }
        }
        bt_en?.setOnClickListener {
//             切换 英語
            val restart = MultiLanguages.setAppLanguage(
                this, LocaleContract.getEnglishLocale()
            )
            if (restart) {
                EasyConfig.getInstance().addHeader("language", "en")
                ActivityManager.getInstance().finishAllActivities()
//                startActivity(SplashActivity::class.java)
                startActivity(AdminActivity::class.java)
            }
        }
        btn_sn?.setOnClickListener {
            val code: String = MmkvUtil.getString(MmkvUtil.DeviceCode, "")

            InputDialog.Builder(this).setTitle("请设置后台分配的设备编码").setContent(code)
                .setHint("请输入").setConfirm(getString(R.string.common_confirm))
                .setCancel(getString(R.string.common_cancel))
                .setListener(object : InputDialog.OnListener {

                    override fun onConfirm(dialog: BaseDialog?, content: String) {
                        if (content == "") {/*TipDialog.show(
                                "设备码空白", com.kongzue.dialogx.dialogs.WaitDialog.TYPE.WARNING
                            )*/

                        } else {
                            MmkvUtil.save(MmkvUtil.DeviceCode, content)
                            //                                  填完后   你得请求接口呀
                            restartApp()
                        }
                    }
                }).show()
        }
        btn_sys_setting?.setOnClickListener {
            loadActivity("com.android.settings", "Settings")
        }
        btn_launcher?.setOnClickListener {
            val pkg = "com.android.launcher3" // 每个rom都是不同的
            loadActivity(pkg, "uioverrides.QuickstepLauncher")

        }
        initHostSpinner()
    }

    private fun restartApp() {
        ToastUtils.show("即将重启应用")
        WebSocketManager.getInstance().closeWebSocket()
        postDelayed({
            ActivityManager.getInstance().finishAllActivities()
            startActivity(MainAct::class.java)
        }, 500)
    }

    private val sp_host: AppCompatSpinner? by lazy { findViewById(com.hjq.demo.R.id.sp_host) }
    val hosts =
        arrayOf("请选择", "http://xcx.pandagongxiang.com/", "http://jndzgxsyy.test.jhwangluo.com/");

    private fun initHostSpinner() {
        val adapter = ArrayAdapter(
//            this, android.R.layout.simple_spinner_item, hosts
            this, R.layout.item_host, hosts
        )
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        adapter.setDropDownViewResource(R.layout.item_host);
        sp_host?.adapter = adapter;
        sp_host?.onItemSelectedListener = hostSpinnerListener;
        sp_host?.setSelection(MmkvUtil.getInt(MmkvUtil.HostsIndex, 0)) // 将上次选的默认选

    }

    private val hostSpinnerListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
//            Timber.d("$position")
//            ToastUtils.show("仅供技术人员测试或紧急情况使用，平时严禁切换")
            MmkvUtil.save(MmkvUtil.Hosts, hosts.get(position))
            MmkvUtil.save(MmkvUtil.HostsIndex, position)

        }

        override fun onNothingSelected(parent: AdapterView<*>?) {
        }

    }

    private fun setTimeWake() {

        /* val intent = Intent(this, BootReceiver.class);
         intent.setAction(Intent.ACTION_BOOT_COMPLETED);*/

        val pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
        val alarmManager = getContext().getSystemService(Context.ALARM_SERVICE) as AlarmManager;
        alarmManager.set(AlarmManager.RTC_WAKEUP, 120 * 1000, pendingIntent);
//       -----------------------------------
//       ©著作权归作者所有：来自51CTO博客作者mob64ca12f0cf8f的原创作品，请联系作者获取转载授权，否则将追究法律责任
//       android定时开关机或重启的代码
//       https://blog.51cto.com/u_16213433/9129399
    }

    private fun shutdown() {
        try {
            val process = Runtime.getRuntime().exec("su")
            val out = DataOutputStream(
                process.outputStream
            )
            out.writeBytes("reboot -p\n")
//            out.writeBytes("shutdown -p\n")
            out.writeBytes("exit\n")
            out.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun restart() {
        try {
            val process = Runtime.getRuntime().exec("su")
            val out = DataOutputStream(
                process.outputStream
            )
            out.writeBytes("reboot \n")
            out.writeBytes("exit\n")
            out.flush()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    fun checkRootPermission(): Boolean {
        var hasRoot = false
        try {
            hasRoot =
                if (!File("/system/app/Superuser.apk").exists() && !File("/system/bin/superuser").exists() && !File(
                        "/system/xbin/daemonsu"
                    ).exists()
                ) {
                    false
                } else {
                    true
                }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return hasRoot
    }

    /**
     * 是否存在su命令，并且有执行权限
     *
     * @return 存在su命令，并且有执行权限返回true
     */
    fun isSuEnable(): Boolean {
        var file: File? = null
        val paths = arrayOf(
            "/system/bin/", "/system/xbin/", "/system/sbin/", "/sbin/", "/vendor/bin/", "/su/bin/"
        )
        try {
            for (path in paths) {
                file = File(path + "su")
                if (file.exists() && file.canExecute()) {
                    Log.i("TAG", "find su in : $path")
                    return true
                }
            }
        } catch (x: java.lang.Exception) {
            x.printStackTrace()
        }
        return false
    }

    private fun play(msg: String) {
        if (toSpeech != null) { //
            if (!toSpeech!!.isSpeaking) {
                toSpeech!!.speak(msg, TextToSpeech.QUEUE_ADD, null, "id-${msg}")
            } else {
//                 将播报过程中接收的语音缓存一下
//                voiceStrList.add(msg);
            }
        }
    }

    private var toSpeech: TextToSpeech? = null
    private fun initTextToSpeech() {
//  https://www.xfyun.cn/doc/tts/AIkit_offline_tts/Android-SDK.html
        toSpeech = TextToSpeech(this) { status ->
            if (status == TextToSpeech.SUCCESS) {
                // 设置首选项为中文
                val result = toSpeech!!.setLanguage(Locale.CHINA)
                if (result < 0) {
                    Timber.e("语音有误 ${result}")

                    /*if (result != TextToSpeech.LANG_COUNTRY_AVAILABLE && result != TextToSpeech.LANG_AVAILABLE) {

                        }*/
                }


                // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                val s = speedPicth / 10
                ToastUtils.show("$s")
                toSpeech!!.setPitch(s);
                // 设置语速
                toSpeech!!.setSpeechRate(0.8f)
            } else {
                Timber.e("语音初始化有误  " + status.toString())
            }
        }
        toSpeech!!.setOnUtteranceProgressListener(object : UtteranceProgressListener() {
            override fun onStart(utteranceId: String?) {
                Timber.d("语音播放 onStart $String")
            }

            override fun onDone(utteranceId: String?) {
                Timber.i("语音播放 onDone $String")
            }

            override fun onError(utteranceId: String?) {
                Timber.e("语音播放 onError $String")
            }

        })
    }

    private fun loadActivity(pkg: String, act: String) {
        val intent = Intent(Intent.ACTION_MAIN)
        val cn = ComponentName(pkg, "$pkg.$act")
        intent.component = cn
        startActivity(intent)
        finish()
    }

    override fun initData() {

        InputDialog.Builder(getContext()).setTitle("Admin password").setContent("")
            .setHint("Admin password").setConfirm(getString(R.string.common_confirm))
            .setCancel(getString(R.string.common_cancel))
            .setListener(object : InputDialog.OnListener {
                override fun onCancel(dialog: BaseDialog?) {
//                            InputDialog.OnListener.super.onCancel(dialog);
                    finish()
                }

                override fun onConfirm(dialog: BaseDialog?, content: String) {
                    if (!content.equals("qqqqqq") && !BuildConfig.DEBUG) {
                        ToastUtils.show("faild")
                        finish()
                    }
                }
            }).show()
    }
}